package wint.session;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wint.session.config.DefaultSessionConfig;
import wint.session.config.SessionConfig;
import wint.session.servlet.WintHttpSession;
import wint.session.servlet.WintSessionHttpServletRequest;
import wint.session.servlet.WintSessionHttpServletResponse;

public class WintSessionProcessor {
	
	private ServletContext servletContext;
	
	private SessionConfig sessionConfig;
	
	public void init(ServletContext servletContext) {
		this.servletContext = servletContext;
		
		DefaultSessionConfig sessionConfig = new DefaultSessionConfig();
		sessionConfig.init();
		this.sessionConfig = sessionConfig;
		
		servletContext.log("Wint Session has been initialized.");
	}
	
	public void destroy() {
		
	}
	
	public void process(HttpServletRequest httpRequest, HttpServletResponse httpResponse, ProcessorHandler processorHandler) throws ServletException, IOException {
		WintSessionHttpServletRequest wintSessionHttpServletRequest = new WintSessionHttpServletRequest(httpRequest);
		WintSessionHttpServletResponse wintSessionHttpServletResponse = new WintSessionHttpServletResponse(httpResponse);
		WintHttpSession wintHttpSession = new WintHttpSession(wintSessionHttpServletRequest, wintSessionHttpServletResponse);
		try {
			wintHttpSession.init(servletContext, sessionConfig);
			wintSessionHttpServletRequest.setWintHttpSession(wintHttpSession);
			processorHandler.onProcess(wintSessionHttpServletRequest, wintSessionHttpServletResponse);
		} finally {
			wintHttpSession.commit();
		}
	}
	
	public static interface ProcessorHandler {
		void onProcess(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException;
	}

}
